package com.chinawayltd.ews.sample.web.basicInfo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TDriverPlan;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TShift;
import com.chinawayltd.ews.sample.model.basicInfo.ShiftVO;
import com.chinawayltd.ews.sample.service.algorithm.DriverPlanService;
import com.chinawayltd.ews.sample.service.basicInfo.ShiftService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;
import com.chinawayltd.ews.sample.web.query.ShiftGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 班次设置API
 * @author: chenxin
 * @create: 2018年4月12日 下午3:54:34
 */
@Api(tags = { "班次设置API" })
@RestController
@RequestMapping(value = "/web/shift")
public class ShiftController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ShiftService shiftService;
    @Autowired
    private CommonService commonService;
	@Autowired
	DriverPlanService driverPlanService;
	private final String tableName = "T_SHIFT";
	
    @ApiOperation(value = "列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(ShiftGirdQuery queryParam) {
    	ResultModel model = new ResultModel();
        try {
            List<ShiftVO> list = shiftService.listShiftByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
        	logger.error("班次列表查询异常！"+e);
        }
        return model;
    }
    
	@ApiOperation(value = "通过班次名称模糊查询", notes = "")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "shiftId", value = "班次id", dataType = "Long", required = false),
		@ApiImplicitParam(paramType = "query", name = "shiftName", value = "班次名称", dataType = "String", required = false)})
	@RequestMapping(value = { "/listShiftByParam" }, method = RequestMethod.POST)
	public ResultModel listShiftByParam(Long shiftId, String shiftName){
		ResultModel model = new ResultModel();
		try {
			List<TShift> list = shiftService.listShiftByName(shiftId, shiftName);
			if(list!=null && !list.isEmpty())
				model.setData(new JSONObject().fluentPut("result" , list));
			else
				model.setData(new JSONObject().fluentPut("result" , null));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
			e.printStackTrace();
		}
		return model;
	}
	
	@ApiOperation(value = "通过班次名称查询对象,可用来校验名称唯一性", notes = "校验名称：添加校验名称不需要ID,修改校验名称必要ID,返回Sub_code=0为可用,1为已存在!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "shiftId", value = "班次id", dataType = "Long", required = false),
		@ApiImplicitParam(paramType = "query", name = "shiftName", value = "班次名称", dataType = "String", required = true)})
	@RequestMapping(value = { "/getShiftByNameAndId" }, method = RequestMethod.POST)
	public ResultModel getShiftByNameAndId(Long shiftId, String shiftName){
		ResultModel model = new ResultModel();
		try {
			List<TShift> list = shiftService.getShiftByNameAndId(shiftId, shiftName);
			if(list!=null && !list.isEmpty()){
				model.setData(new JSONObject().fluentPut("result" , "已存在"));
			}else{
				model.setData(new JSONObject().fluentPut("result" , "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
			e.printStackTrace();
		}
		return model;
	}
	
    @ApiOperation(value = "班次根据ID查询接口")
    @RequestMapping(value = "/find/{id}" , method={RequestMethod.GET})
    @ApiImplicitParam(paramType="path",name="id",value="班次ID",dataType="Long",required=true)
    public ResultModel getTShiftById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
    	try {
            TShift shift = shiftService.selectTShift(id);
            model.setData(new JSONObject().fluentPut("result" , shift));
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
            logger.error("根据ID查询站点信息出错！id：" + id, e);
        }
        return model;
    }
    

    @ApiOperation(value = "添加班次接口")
    @RequestMapping(value = "/add" , method={RequestMethod.POST})
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="shiftName",value="班次名称",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="shiftType",value="班次类型",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="bigTime",value="班次开始时间",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="endTime",value="班次结束时间",dataType="String",required=true)
    })
    public ResultModel addTShift(TShift shift) {
    	ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(shift.getShiftName())){
				throw new BusinessException("添加失败");
			}
			ResultModel rm  = this.getShiftByNameAndId(null, shift.getShiftName());
			if(rm.getSub_code()==1){
				throw new BusinessException("班次名称已存在，添加失败");
			}
			if(StringUtils.isBlank(shift.getBigTime()) || StringUtils.isBlank(shift.getEndTime())){
				throw new BusinessException("开始或结束时间不能为空，添加失败");
			}
			// 判断新增的班次是否跟数据里面的班次冲突
			boolean flag = shiftService.judgeTimeConflict(shift);
			if(flag){
				throw new BusinessException("时间存在冲突，添加失败");
			}
			int result = shiftService.addTShift(shift);
	        if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
	        }
		} catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
			logger.error("班次管理新增发生异常！", e);
		}
        return model;
    }

    @ApiOperation(value = "更新班次接口")
    @RequestMapping(value = "/update" , method={RequestMethod.POST})
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="id",value="班次id",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="shiftName",value="班次名称",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="shiftType",value="班次类型",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="bigTime",value="班次开始时间",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="endTime",value="班次结束时间",dataType="String",required=true)
    })
    public ResultModel updateTShift(TShift shift) {
    	ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(shift.getId().toString())){
				throw new BusinessException("修改失败");
			}
			ResultModel rm  = this.getShiftByNameAndId(shift.getId(), shift.getShiftName());
			if(rm.getSub_code()==1){
				throw new BusinessException("修改失败");
			}
			if(StringUtils.isBlank(shift.getBigTime()) || StringUtils.isBlank(shift.getEndTime())){
				throw new BusinessException("开始或结束时间不能为空，修改失败");
			}
			// 判断新增的班次是否跟数据里面的班次冲突
			boolean flag = shiftService.judgeTimeConflict(shift);
			if(flag){
				throw new BusinessException("时间存在冲突，修改失败");
			}
			int result = shiftService.updateTShift(shift);
			if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
	        }
		} catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			logger.error("班次管理修改发生异常！", e);
		}
        return model;
    }

    @ApiOperation(value = "删除班次接口")
    @RequestMapping(value = "/delete/{id}" , method={RequestMethod.DELETE})
    @ApiImplicitParam(paramType="path",name="id",value="班次ID",dataType="Long",required=true)
    public ResultModel deleteTShift(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
        try {
			List<TDriverPlan> list = driverPlanService.listDriverPlanByShiftId(id);
			if(list.size() >0) {
				throw new BusinessException("司机排班信息含有该班次，删除失败!");
			}
        	int result = shiftService.deleteTShift(id);
            if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
		} catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
			logger.error("班次管理删除发生异常！ID="+id, e);
		}
        return model;
    }

    @ApiOperation(value = "通过ID查询操作日记接口")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName(tableName);
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
    
	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		try {
			// 1.分割ids
			String[] idArr = ids.split(",");
			for (String string : idArr) {
				long shiftId = Long.parseLong(string);
				List<TDriverPlan> list = driverPlanService.listDriverPlanByShiftId(shiftId);
				if(list!=null && !list.isEmpty()){
					throw new BusinessException("司机排班信息含有该班次，删除失败!");
				}
			}
			int result = shiftService.deletesByIds(idArr);
			if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
        } catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
            logger.error("批量删除接口异常！", e);
        }
		return model;
		
	}
	
	@ApiOperation(value = "班次设置导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody ShiftGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<ShiftVO> branchList = shiftService.listShiftByPage(queryParam);
            //List<Map<String, Object>> branchList = shiftService.exportGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(branchList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "班次设置列表" , request, response);
        }catch (Exception e){
            logger.error("班次设置列表导出出错！", e);
        }
    }
	
	/**解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * @author Fay
	 * @date 2018年5月3日 上午10:07:15
	 * @param file
	 * @param request
	 * @param response
	 */
	@ApiOperation(value = "班次信息批量导入")
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
	public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		JSONObject object = new JSONObject();
		try {
    		// 1、解析导入的数据
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
	    	if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = shiftService.insertList(list);
			// 3、导出错误数据
			if(result.getList().size() >0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "班次信息" , request, response);
			}
		} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
}
